<template>
  <div class="file-upload-container">
    <div 
      class="upload-area"
      :class="{ 'drag-over': isDragOver, 'has-file': uploadedFile }"
      @drop="handleDrop"
      @dragover="handleDragOver"
      @dragleave="handleDragLeave"
      @click="triggerFileInput"
    >
      <input
        ref="fileInput"
        type="file"
        accept=".txt,.doc,.docx"
        style="display: none"
        @change="handleFileSelect"
      />
      
      <div v-if="!uploadedFile" class="upload-placeholder">
        <div class="upload-icon">
          <CloudUploadOutlined :style="{ fontSize: '48px', color: '#6366f1' }" />
        </div>
        <h3 class="upload-title">拖拽文件到此处或点击上传</h3>
        <p class="upload-subtitle">支持 txt、docx、docx 格式文件</p>
        <a-button type="primary" class="upload-btn">选择文件</a-button>
      </div>
      
      <div v-else class="file-info">
        <div class="file-icon">
          <FileText :size="32" />
        </div>
        <div class="file-details">
          <h4 class="file-name">{{ uploadedFile.name }}</h4>
          <p class="file-size">{{ formatFileSize(uploadedFile.size) }}</p>
        </div>
        <a-button 
          type="text" 
          danger 
          @click.stop="removeFile"
          class="remove-btn"
        >
          <X :size="16" />
        </a-button>
      </div>
    </div>
    
    <div v-if="uploadProgress > 0 && uploadProgress < 100" class="upload-progress">
      <a-progress :percent="uploadProgress" :show-info="false" />
      <span class="progress-text">上传中... {{ uploadProgress }}%</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { CloudUploadOutlined } from '@ant-design/icons-vue'
import { FileText, X } from 'lucide-vue-next'
import { message } from 'ant-design-vue'

interface Props {
  accept?: string
  maxSize?: number // MB
}

interface Emits {
  fileUploaded: [file: File, content: string]
  fileRemoved: []
}

const props = withDefaults(defineProps<Props>(), {
  accept: '.txt,.doc,.docx',
  maxSize: 10
})

const emit = defineEmits<Emits>()

const fileInput = ref<HTMLInputElement>()
const isDragOver = ref(false)
const uploadedFile = ref<File | null>(null)
const uploadProgress = ref(0)

const handleDragOver = (e: DragEvent) => {
  e.preventDefault()
  isDragOver.value = true
}

const handleDragLeave = (e: DragEvent) => {
  e.preventDefault()
  isDragOver.value = false
}

const handleDrop = (e: DragEvent) => {
  e.preventDefault()
  isDragOver.value = false
  
  const files = e.dataTransfer?.files
  if (files && files.length > 0) {
    if (files[0]) {
      handleFile(files[0])
    }
  }
}

const triggerFileInput = () => {
  if (!uploadedFile.value) {
    fileInput.value?.click()
  }
}

const handleFileSelect = (e: Event) => {
  const target = e.target as HTMLInputElement
  const files = target.files
  if (files && files.length > 0) {
    if (files[0]) {
      handleFile(files[0])
    }
  }
}

const handleFile = async (file: File) => {
  // 验证文件类型
  const allowedTypes = ['.txt', '.doc', '.docx']
  const fileExtension = '.' + file.name.split('.').pop()?.toLowerCase()
  
  if (!allowedTypes.includes(fileExtension)) {
    message.error('不支持的文件格式，请上传 txt、doc 或 docx 文件')
    return
  }
  
  // 验证文件大小
  if (file.size > props.maxSize * 1024 * 1024) {
    message.error(`文件大小不能超过 ${props.maxSize}MB`)
    return
  }
  
  uploadedFile.value = file
  
  // 模拟上传进度
  uploadProgress.value = 0
  const progressInterval = setInterval(() => {
    uploadProgress.value += 10
    if (uploadProgress.value >= 100) {
      clearInterval(progressInterval)
      setTimeout(() => {
        uploadProgress.value = 0
      }, 500)
    }
  }, 100)
  
  try {
    // 读取文件内容
    const content = await readFileContent(file)
    emit('fileUploaded', file, content)
    message.success('文件上传成功')
  } catch (error) {
    message.error('文件读取失败')
    uploadedFile.value = null
  }
}

const readFileContent = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      resolve(e.target?.result as string)
    }
    reader.onerror = reject
    reader.readAsText(file, 'UTF-8')
  })
}

const removeFile = () => {
  uploadedFile.value = null
  uploadProgress.value = 0
  if (fileInput.value) {
    fileInput.value.value = ''
  }
  emit('fileRemoved')
}

const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
</script>

<style scoped>
.file-upload-container {
  width: 100%;
}

.upload-area {
  border: 2px dashed #d9d9d9;
  border-radius: 12px;
  padding: 32px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafafa;
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-area:hover {
  border-color: #6366f1;
  background: rgba(99, 102, 241, 0.02);
}

.upload-area.drag-over {
  border-color: #6366f1;
  background: rgba(99, 102, 241, 0.05);
  transform: scale(1.02);
}

.upload-area.has-file {
  border-color: #52c41a;
  background: rgba(82, 196, 26, 0.02);
  cursor: default;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
}

.upload-icon {
  margin-bottom: 8px;
}

.upload-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
}

.upload-subtitle {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.upload-btn {
  border-radius: 8px;
  font-weight: 500;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

.file-icon {
  color: #6366f1;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  background: rgba(99, 102, 241, 0.1);
  border-radius: 8px;
}

.file-details {
  flex: 1;
  text-align: left;
}

.file-name {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 500;
  color: #1a1a1a;
  word-break: break-all;
}

.file-size {
  margin: 0;
  font-size: 12px;
  color: #666;
}

.remove-btn {
  color: #ff4d4f !important;
  padding: 4px !important;
  border-radius: 4px !important;
}

.remove-btn:hover {
  background: rgba(255, 77, 79, 0.1) !important;
}

.upload-progress {
  margin-top: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.progress-text {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
}
</style>